package day02;


import lombok.extern.slf4j.Slf4j;
import utils.Sleeper;

import java.util.LinkedList;

@Slf4j
public class Test6 {

    public static void main(String[] args) {


        MessageQueue queue = new MessageQueue(2);

        for (int i = 0; i < 3; i++) {
            int id = i;
            new Thread(()->{
                try {
                    queue.put(new Message(id,"值"+id));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            },"生产者" + i).start();
        }


        new Thread(()->{
            try {
                while(true){
                    Sleeper.sleep(1);
                    Message message = queue.get();
                }

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        },"消费者").start();
    }



}




// 消息队列
@Slf4j
class MessageQueue{

    // 消息队列
    private LinkedList<Message> linkedList =  new LinkedList<>();
    // 队列容量
    private int capacity;
    // 赋值容量
    public MessageQueue(int capacity){
        this.capacity = capacity;
    }

    // 获取信息
    public Message get() throws InterruptedException {
        // 判断队列是不是为空
        synchronized (linkedList){
            while(linkedList.isEmpty()){
                log.debug("队列为空,生产者线程等待");
                linkedList.wait();
            }
            Message message = linkedList.removeFirst();
            log.debug("已经消费消息:{}",message);
            linkedList.notifyAll();
            return message;
        }
    }

    // 添加信息
    public void put(Message message) throws InterruptedException {

        synchronized (linkedList){
            // 判断是不是为满
            while(linkedList.size() == capacity){
                log.debug("队列已满,消费者线程等待");
                linkedList.wait();
            }
            // 将消息队列添加到尾部
            linkedList.addLast(message);
            log.debug("已经生成消息:{}",message);
            linkedList.notifyAll();
        }

    }
}

final class Message{
    private int id;
    private Object message;


    public Message(int id, Object message) {
        this.id = id;
        this.message = message;
    }

    public int getId() {
        return id;
    }

    public Object getMessage() {
        return message;
    }
}


